import 'dart:async';

import 'package:flutter/widgets.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:todo_app/utils/mqtt/LocalMqttClient.dart';

MqtttUserClientController useMqtttUserClientController(int userId) {
  return use( _MqtttUserClientControllerHook(userId));
}

class _MqtttUserClientControllerHook extends Hook<MqtttUserClientController> {
  const _MqtttUserClientControllerHook(this.userId);
  final int userId;

  @override
  HookState<MqtttUserClientController, Hook<MqtttUserClientController>> createState() {
    return _MqtttUserClientControllerHookState();
  }
}

typedef SetStateFunction = void Function(VoidCallback fn);

class _MqtttUserClientControllerHookState extends HookState<MqtttUserClientController, _MqtttUserClientControllerHook> {
  late MqtttUserClientController controller;
  
  @override
  void initHook() {
    super.initHook();
    controller = MqtttUserClientController();
    controller.userId = hook.userId;
    controller.setState = (VoidCallback fn) {
      setState(fn);
    };
    controller.init();
  }

  @override
  MqtttUserClientController build(BuildContext context) {
    return controller;
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}

class MqtttUserClientController {
  late SetStateFunction setState;
  late int userId;
  late StreamSubscription<UserClientPingPong> subscription;
  UserClientPingPong? pingPong;

  init() {
    LocalMqttClient.subscribeUserClient(userId);
    subscription = LocalMqttClient.eventBus.on<UserClientPingPong>().asBroadcastStream().listen((event) {
      pingPong = event;
      setState((){});
    });
  }
  dispose() {
    LocalMqttClient.unsubscribeUserClient(userId);
    subscription.cancel();
  }
}